package srzy.socket

import java.net.Socket
import srzy.common.Config
import srzy.diameter._

abstract class DCCSocketConn extends SocketConn {

  val pro: Protocol = DCCProtocol

  def write(arr: Array[Byte]) = {
    writeLock.lock()
    try {
      outStream.write(arr, 0, arr.length)
      outStream.flush()
    } finally {
      writeLock.unlock()
    }
  }

  def read(): Array[Byte] = {
    readLock.lock()
    try {
      val header = this.read(pro.getHeadLength)
      //      println(getDCCHeadLength(header))
      val body = this.read(pro.getBodyLength(header) - pro.getHeadLength)
      Array.concat(header, body)
    } finally {
      readLock.unlock()
    }
  }
}

object DCCSocketConn {

  //  val serverIp = Config.getValue("root", "config", "SM_IP")
  //  val port = Integer.valueOf(Config.getValue("root", "config", "SM_Port"))
  val CEANullMsg = (<command name="CEA"></command>)
  val CCANullMsg = (<command name="CCA"></command>)
  val DWAMsg = (<command name="DWA">
                  <avp name="Result-Code" value="2001"></avp>
                  <avp name="Origin-Host" value="sm-all-test"></avp>
                  <avp name="Origin-Realm" value="chinaunicom.com"></avp>
                </command>)

  def RAAMsg(sid: String) = (<command name="RAA">
                               <avp name="Session-Id" value={ sid }></avp>
                               <avp name="Result-Code" value="2001"></avp>
                               <avp name="Origin-Host" value="sm-all-test"></avp>
                               <avp name="Origin-Realm" value="chinaunicom.com"></avp>
                               <avp name="User-Name" value="User-Name"></avp>
                               <avp name="Origin-State-Id" value="62"></avp>
                               <avp name="Error-Message" value="0"></avp>
                               <avp name="Error-Reporting-Host" value="0"></avp>
                             </command>)

  def ASAMsg(sid: String) = (<command name="ASA">
                               <avp name="Session-Id" value={ sid }></avp>
                               <avp name="Result-Code" value="2001"></avp>
                               <avp name="Origin-Host" value="sm-all-test"></avp>
                               <avp name="Origin-Realm" value="chinaunicom.com"></avp>
                               <avp name="User-Name" value="User-Name"></avp>
                               <avp name="Origin-State-Id" value="62"></avp>
                               <avp name="Error-Message" value="0"></avp>
                               <avp name="Error-Reporting-Host" value="0"></avp>
                             </command>)

  def apply(serverIp: String, port: Int): DCCSocketConn = {
    val s = new DCCSocketConn {
      val socket = SocketConn.connect(serverIp, port)
      val outStream = socket.getOutputStream()
      val inStream = socket.getInputStream()
    }
    s
  }

}
